<template>
  <t-form-item :label="plugin.t('inbound.supplier_name')" name="supplier_name">
    <t-select 
      v-model="formData.supplier_id" 
      :options="options"
      :loading="loading" 
      @search="onSupplier"
      @change="onSupplierSelect"
      filterable
      clearable
    >
      <template #prefixIcon>
        <t-icon name="user" style="margin-right: 8px" />
      </template>
    </t-select>
  </t-form-item>
</template>
<script setup>
  import { ref } from 'vue'
  import app from '@/app'
  import index from '../../../index'
  import { get } from '@/api/erp/supplier'
  import store from './store'

  const plugin = index.plugin
  const options = ref([])
  const formData = store.data

  const loading = ref(false)
  
  // 加载供货商
  const onSupplier = name => {
    loading.value = true
    get({ name }).then(res => {
      options.value = res.data.map(item => {
        return {
          value: item.id,
          label: item.name 
        }
      })
      // 如果已选择
      if(formData.value.supplier_id && options.value.findIndex(item => formData.value.supplier_id == item.value) == -1) {
        options.value.push({
          value: formData.value.supplier_id,
          label: formData.value.supplier_name
        })
      }
    }).finally(() => {
      loading.value = false
    })
  }

  // 选择供货商
  const onSupplierSelect = () => {
    if(formData.value.supplier_id) {
      formData.value.supplier_name = options.value.find(item => item.value == formData.value.supplier_id).label
    } else {
      formData.value.supplier_id = undefined
      formData.value.supplier_name = undefined
    }
  }

  onSupplier()
</script>